﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

public partial class Error : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Exception error = Server.GetLastError();
        if (error == null)
        {
            error = ObjectCache.Get<Exception>("error");
            ObjectCache.Remove("error");
            //error = Context.Items["error"] as Exception;
            //Context.Items.Remove("error");
        }
        if (error != null)
        {
            Exception baseError = error.GetBaseException();
            if (baseError != null)
                error = baseError;
            string description = string.Format("<b>Source</b>：{0}<br/><b>StackTrace</b>：{1}", error.Source, error.StackTrace);
            errTitle.Text = "错误信息已经被记录, 请联系管理员";
            //errTitle.Text = error.Message;
            //errDescription.Text = description;
            try
            {
                Log(error.Message, description);
            }
            catch
            {
                errTitle.Text = "数据库连接失败，请联系管理员";
                //connection failed
            }
        }
    }

    private void Log(string title, string description)
    {
        const string sql = "INSERT INTO [lt_errorLogs]([l_title], [l_description], [l_url], [l_ipaddress], [l_userAgent]) VALUES (@l_title, @l_description, @l_url, @l_ipaddress, @l_userAgent)";
        SqlParameter[] parameters = new SqlParameter[]{
            SqlParameterEx.CreateParameter("@l_title", SqlDbType.VarChar,100, title),
            SqlParameterEx.CreateParameter("@l_description", SqlDbType.VarChar,5000, description),
            SqlParameterEx.CreateParameter("@l_url", SqlDbType.VarChar, 255, string.Format("{0}-{1}<-{2}", Request.HttpMethod, Request.RawUrl, Request.UrlReferrer)),
            SqlParameterEx.CreateParameter("@l_ipaddress", SqlDbType.VarChar, 50, Request.UserHostAddress),
            SqlParameterEx.CreateParameter("@l_userAgent", SqlDbType.VarChar, 100, Request.UserAgent)
        };
        SqlHelper.Instance.ExecuteNonQuery(sql, parameters);
    }
}